import axios from 'axios'
import router from '@/router'

let http = axios.create({
  baseURL: 'http://localhost:1337',
  // baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 60000,
})

// 添加请求拦截器
http.interceptors.request.use(
  function (config) {
    let token = localStorage.getItem('mall-token')
    if (token) {
      config['headers']['token'] = token
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  },
)

http.interceptors.response.use(
  function (res) {
    if (res.data.code === 401) {
      localStorage.removeItem('mall-token')
      router.push('/login')
    }
    return res
  },
  function (error) {
    console.log(error.response.data);
    if (error.response.data.code === 0) {

      localStorage.removeItem('mall-token')
        // eslint-disable-next-line no-undef
        showFailToast('请先登录')
      router.push('/login')
    }
    // localStorage.removeItem('mall-token');
    // router.push('/login')
    return Promise.reject(error)
  },
)

export default http
